package com.unicom.office.impl;

import com.unicom.office.builder.ExcelBuilder;
import com.unicom.office.config.OfficeConfig;
import com.unicom.office.runtime.OfficeRuntime;
import com.unicom.office.unit.*;

import java.io.File;
import java.io.FileWriter;
import java.util.List;

public class CSVBuilder extends ExcelBuilder {
    public CSVBuilder(){
        super(null, null);
    }

    public CSVBuilder(OfficeConfig config, OfficeRuntime runtime) {
        super(config, runtime);
    }

    protected Object buildWorkbook(WorkbookUnit unit) {
        StringBuffer buffer = new StringBuffer();
        WorksheetUnit worksheetUnit = (WorksheetUnit) unit.getChildren().get(0);
        List<OfficeUnit> rows = worksheetUnit.getChildren();
        for (int i = 0; i < rows.size(); i++) {
            List<OfficeUnit> cells = rows.get(i).getChildren();
            for (int j = 0; j < cells.size(); j++) {
                buffer.append(cells.get(j).toString());
                if(j < cells.size() - 1) {
                    buffer.append(',');
                }
            }
            if(i < rows.size() - 1) {
                buffer.append("\r\n");
            }
        }
        return buffer.toString();
    }

    protected Object buildWorksheet(WorksheetUnit unit, Object parent) {
        return null;
    }

    protected Object buildRow(RowUnit unit, Object parent) {
        return null;
    }

    protected Object buildCell(CellUnit unit, Object parent) {
        return null;
    }

    protected Object buildParagraph(ParagraphUnit unit, Object parent) {
        return null;
    }

    protected Object buildTextbox(TextboxUnit unit, Object parent) {
        return null;
    }

    protected Object buildTextrange(TextRangeUnit unit, Object parent) {
        return null;
    }

    protected Object buildPicture(PictureUnit unit, Object parent) {
        return null;
    }

    public void writeFile(Object result, String targetPath) {
        File file = new File(targetPath);
        try {
            if(!file.exists()) {
                file.createNewFile();
            }

            FileWriter fileWriter = new FileWriter(targetPath);
            fileWriter.append(result.toString());
            fileWriter.close();
        }catch(Exception ex){
            throw new RuntimeException(ex.getMessage());
        }
    }
}
